/**
 * Created by Thinkpad on 2016/5/25 0025.
 */

var $table;
$(function () {

    $table = $("#table");

    $("#customerModal").on('show.bs.modal', function (event) {

        $(':input', '#customerForm')
            .not(':button, :submit, :reset')
            .val('')
            .removeAttr('checked')
            .removeAttr('selected');

        var button = $(event.relatedTarget);

        var rowId = button.data('id');
        if (rowId == null) {
            $("#customerModalLabel").text('新增');
        } else {
            $("#customerModalLabel").text('修改');

            var row = $table.bootstrapTable('getRowByUniqueId', rowId);
            $("#customerForm").find("input[name='customerId']").val(rowId);
            $("#customerForm").find("input[name='card_no']").val(row.cardNo);
            $("#customerForm").find("input[name='name']").val(row.name);
            $("#customerForm").find("input[name='mobile']").val(row.mobile);
        }
    })

    $("#customerForm").submit(function () {
        $.post("/customer.do", $(this).serialize(), function (data) {
            if (data.code == 0) {
                $table.bootstrapTable('refresh', {silent: true});
            } else {
                alert(data.desc);
            }
        }, "json");

        $("#customerModal").modal('hide');

        return false;
    });

    $("#delModal").on("show.bs.modal", function (event) {
        var $this = $(this);
        var selections = $table.bootstrapTable('getSelections');
        if(selections == null || selections.length == 0) {
            $this.find('p.lead').text('没有选中任何记录');
            $this.find('button[type="submit"]').attr('disabled', true);
            return;
        }

        var customers = new Array();
        var idArray = new Array();
        for (var i in selections) {
            var row = selections[i];
            idArray.push(row.id);
            customers.push(row.cardNo + '(' + row.name + ')')
        }

        $this.find('input[name="ids"]').val(idArray.join());
        $this.find('p.lead').text(customers.join());
        $this.find('button[type="submit"]').attr('disabled', false);
    });

    $('#delForm').submit(function () {
        $.post("/customer_del.do", $(this).serialize(), function (data) {
            if (data.code == 0) {
                $table.bootstrapTable('refresh', {silent: true});
            } else {
                alert(data.desc);
            }
        }, "json");

        $("#delModal").modal('hide');

        return false;
    });

});

function operationFormatter(val, row, idx) {
    return '<button class="btn btn-sm btn-operate" ' +
        'data-toggle="modal" data-target="#customerModal" data-id="' + row.id + '">' +
        '<span class="glyphicon glyphicon-pencil" ></span></button>';
}